<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	const ERROR_NO_GENERATE_TOKEN=11;
	private $_id;
	private $_model;
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		
		$user = Usuario::model()->findByAttributes(array('usuario_nombre'=>$this->username));
		
        if($user===null)
        {
        	$this->errorCode= self::ERROR_USERNAME_INVALID;
        }
        
        if($user->usuario_clave !== hash('sha512',$this->password))
        {
           $this->errorCode= self::ERROR_PASSWORD_INVALID;
        }
        else
        {
        	
        	$user->usuario_tokensession = uniqid('',true);
        	if($user->save())
        	{
        		
        		//echo 'entre';exit;
        		$this->setState('sessionToken', $user->usuario_tokensession );
	        	$this->_model = $user;
	            $this->_id = $user->usuario_id;
        		$this->errorCode= self::ERROR_NONE;
        	}
        	else
        	{
        		var_dump($user->getErrors());
        		exit;
        		//var_dump($user->getErrors());exit;
        		$this->errorCode= self::ERROR_NO_GENERATE_TOKEN;
        	}
        }
        return $this->errorCode;
	}
	
	public function getId()
    {
        return $this->_id;
    }
	public function getModel()
    {
        return $this->_model;
    }
}